package com.example.maybeaccount;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.app.DatePickerDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.maybeaccount.Entry.Entrance;
import com.example.maybeaccount.Fragment.Fragment_credit;
import com.example.maybeaccount.Fragment.Fragment_income;
import com.example.maybeaccount.Fragment.Fragment_outcome;
import com.example.maybeaccount.Mode.Account;
import com.example.maybeaccount.Mode.AlarmService;
import com.example.maybeaccount.Mode.Item;
import com.example.maybeaccount.Mode.SqliteDB;
import com.example.maybeaccount.datepicker.CustomDatePicker;
import com.example.maybeaccount.datepicker.DateFormatUtils;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/** 记账活动 */
public class AddItem extends AppCompatActivity {

    private List<String> datas =new ArrayList<String>();

    private ArrayList<Fragment> list;

    private MyAdapter adapter;

    public static Fragment instantFragment;

    FragmentManager fm=getSupportFragmentManager();

    private String amount;
    private String lv1_option;
    private String lv2_option;
    private String account;
    private String member;
    private String time;
    private String business;
    private String project;
    private String remark;
    private int firstFlag = 0; //判断是否第一次进入
    private Item item;

    Fragment_outcome fg_outcome = new Fragment_outcome(this);
    Fragment_income fg_income = new Fragment_income(this);
    Fragment_credit fg_credit = new Fragment_credit();


    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initBroadcast();
        setContentView(R.layout.activity_add_item);
        ActionBar actionbar=getSupportActionBar();
        if(actionbar!=null){
            actionbar.hide();
        }
        Init();

    }

    private  void Init(){
        TabLayout tabLayout=(TabLayout) findViewById(R.id.tablayout);
        ViewPager viewPager = (ViewPager) findViewById(R.id.vp);

        datas.add("支出");
        datas.add("收入");
        datas.add("信贷");

        list = new ArrayList<Fragment>();

        list.add(fg_outcome);

        list.add(fg_income);

        list.add(fg_credit);

        adapter=new MyAdapter(fm,list);
        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(2);


        //进行关联
        tabLayout.setupWithViewPager(viewPager);

        //保存
        Button button_save =findViewById(R.id.button_save);
        button_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(adapter.getInstantFragment() instanceof Fragment_outcome){
                    //支出
                    Map<String,String> dataset = fg_outcome.givedatas();
                    if(dataset.get("amount") == null){
                        Toast.makeText(AddItem.this,"请输入金额",Toast.LENGTH_LONG).show();
                        return;
                    }
                    item = new Item();
                    item.initItemByMap(dataset,Item.MODE_OUTCOME);

                }else if(adapter.getInstantFragment() instanceof Fragment_income){
                    //收入
                    Map<String,String> dataset = fg_income.givedatas();
                    if(dataset.get("amount") == null){
                        Toast.makeText(AddItem.this,"请输入金额",Toast.LENGTH_LONG).show();
                        return;
                    }
                    item = new Item();
                    item.initItemByMap(dataset,Item.MODE_INCOME);

                }else if(adapter.getInstantFragment() instanceof Fragment_credit){
                    //信贷
                    Map<String,String> dataset = fg_credit.givedatas();
                    if(dataset.get("amount") == null){
                        Toast.makeText(AddItem.this,"请输入金额",Toast.LENGTH_LONG).show();
                        return;
                    }
                    item = new Item();
                    item.initItemByMap(dataset,Item.MODE_CREDIT);

                }
                if(saveItem(item)){
                    firstFlag = 0;
                    Intent intent = new Intent(AddItem.this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{

                }

            }
        });

        //返回
        final Button butBack = (Button)findViewById(R.id.button_back);
        butBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                firstFlag = 0;
                Intent intent= new Intent(AddItem.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        });


    }

    @Override
    protected void onResume(){
        super.onResume();
        if(firstFlag == 1){
            firstFlag = 0;
            Intent intent = new Intent(AddItem.this, Entrance.class);
            intent.putExtra("resume","AddItem");
            startActivity(intent);
        }else{
            firstFlag = 0;
        }
    }

    /**
     * 重写停止活动，在停止时开启提醒服务
     */
    @Override
    public void onPause(){
        super.onPause();
        Intent intent = new Intent(this, AlarmService.class);
        startService(intent);
    }

    /**
     * 重写返回键，确保回到主界面，而不是登录
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
        }
        return true;
    }

    private boolean saveItem(Item item){
        Account account = SqliteDB.getInstance(getApplicationContext()).getAccountOfName(item.getAccount());
        account.updateData(item.getAmount());
        //更新账户信息
        int result = SqliteDB.getInstance(getApplicationContext()).updateAccount(account);
        if(result == 1){
            //更新账单信息
            result = SqliteDB.getInstance(getApplicationContext()).saveItem(item);
            if(result == 1){
                Toast.makeText(getApplicationContext(),"记账成功",Toast.LENGTH_LONG).show();
                return true;
            }else{
                Toast.makeText(getApplicationContext(),"记账失败！",Toast.LENGTH_LONG).show();
                return false;
            }
        }else{
            Toast.makeText(getApplicationContext(),"记账失败！",Toast.LENGTH_LONG).show();
            return false;
        }
    }

//    public void getdatas(String choose_amount,String lv1_option,String lv2_option,String account_option
//    ,String input_time,String member_option,String input_business,String input_project,String input_remark) {
//        this.amount=choose_amount;
//        this.lv1_option=lv1_option;
//        this.lv2_option=lv2_option;
//        this.account=account_option;
//        this.time=input_time;
//        this.member=member_option;
//        this.business=input_business;
//        this.project=input_project;
//        this.remark=input_remark;
//    }

    class MyAdapter extends FragmentPagerAdapter {

        private List<Fragment> list;

        //带参的构造方法
        public MyAdapter(FragmentManager fm, ArrayList<Fragment> list) {
            super(fm);
            this.list=list;
        }

        @Override
        public Fragment getItem(int position) {
            return list.get(position);
        }

        @Override
        public int getCount() {
            return datas.size();//返回选项卡的数量
        }

        @Override
        public void setPrimaryItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            instantFragment = (Fragment) object;
            super.setPrimaryItem(container, position, object);
        }

        public Fragment getInstantFragment(){
            return instantFragment;
        }

        //重写该方法可以让TabLayout有标题文字

        @Nullable

        @Override

        public CharSequence getPageTitle(int position) {

            return datas.get(position);

        }
    }

    /** 广播监听home和menu */
    class InnerRecevier extends BroadcastReceiver {
        final String SYSTEM_DIALOG_REASON_KEY = "reason";
        final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
        final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {

                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);

                if (reason != null) {

                    if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
                        // "Home键被监听"
                        firstFlag = 1;

                    } else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
                        //"多任务键被监听"
                        firstFlag = 1;

                    }
                }
            }
        }
    }

    private void initBroadcast(){
        /** 广播 */
        this.getWindow().setFlags(0x80000000,0x80000000);
        //创建广播
        InnerRecevier innerReceiver = new InnerRecevier();
        //动态注册广播
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        //启动广播
        registerReceiver(innerReceiver, intentFilter);
    }

}